// 存储当前优化状态
let isOptimized = false;
let currentMaxWidth = 1100;

// 创建一个样式标签用于动态更新最大宽度
const createStyleTag = () => {
    const style = document.createElement('style');
    style.id = 'width-optimizer-style';
    document.head.appendChild(style);
    return style;
};

// 更新最大宽度样式
const updateMaxWidth = (width) => {
    const style = document.getElementById('width-optimizer-style') || createStyleTag();
    style.textContent = `
        .width-optimizer-enabled {
            max-width: ${width}px !important;
            margin-left: auto !important;
            margin-right: auto !important;
            float: none !important;
            position: relative !important;
            left: 0 !important;
            right: 0 !important;
            transform: none !important;
        }
        
        /* 处理父容器 */
        .width-optimizer-enabled-parent {
            display: flex !important;
            justify-content: center !important;
            width: 100% !important;
            max-width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
        }
    `;
};

// 获取需要优化的元素
const getTargetElements = () => {
    const possibleSelectors = [
        'main',
        'article',
        '.main-content',
        '.content',
        '#content',
        '.post-content',
        '.article-content',
        '.entry-content',
        '[role="main"]',
        '.container',
        '.wrapper'
    ];

    // 尝试找到主要内容容器
    for (let selector of possibleSelectors) {
        const element = document.querySelector(selector);
        if (element) {
            // 检查元素是否包含主要内容
            const text = element.textContent;
            if (text && text.length > 500) { // 假设主要内容至少有500个字符
                return [element];
            }
        }
    }

    // 如果找不到合适的容器，使用body
    return [document.body];
};

// 应用宽度优化
const applyOptimization = (enabled, maxWidth = currentMaxWidth) => {
    const elements = getTargetElements();
    currentMaxWidth = maxWidth;
    
    elements.forEach(element => {
        if (enabled) {
            // 添加优化类
            element.classList.add('width-optimizer-enabled');
            
            // 处理父元素
            let parent = element.parentElement;
            if (parent && parent !== document.body) {
                parent.classList.add('width-optimizer-enabled-parent');
            }
            
            // 强制设置内联样式以确保居中
            element.style.setProperty('margin-left', 'auto', 'important');
            element.style.setProperty('margin-right', 'auto', 'important');
            element.style.setProperty('float', 'none', 'important');
            element.style.setProperty('position', 'relative', 'important');
            element.style.setProperty('left', '0', 'important');
            element.style.setProperty('right', '0', 'important');
            element.style.setProperty('transform', 'none', 'important');
        } else {
            // 移除优化类
            element.classList.remove('width-optimizer-enabled');
            
            // 移除父元素类
            let parent = element.parentElement;
            if (parent && parent !== document.body) {
                parent.classList.remove('width-optimizer-enabled-parent');
            }
            
            // 移除内联样式
            element.style.removeProperty('margin-left');
            element.style.removeProperty('margin-right');
            element.style.removeProperty('float');
            element.style.removeProperty('position');
            element.style.removeProperty('left');
            element.style.removeProperty('right');
            element.style.removeProperty('transform');
        }
    });

    if (enabled) {
        updateMaxWidth(maxWidth);
    }
    
    isOptimized = enabled;
};

// 添加 URL 匹配函数
function matchUrl(pattern, url) {
    const regexPattern = pattern
        .replace(/[.+?^${}()|[\]\\]/g, '\\$&')
        .replace(/\*/g, '.*');
    const regex = new RegExp(`^${regexPattern}`);
    return regex.test(url);
}

// 修改检查函数，确保白名单优先级最高
function shouldOptimizePage(settings, currentUrl) {
    const { mode, whitelist, optimizeList } = settings;
    
    // 首先检查白名单，如果在白名单中直接返回 false
    if (whitelist && whitelist.some(item => matchUrl(item.url, currentUrl))) {
        return false;
    }
    
    // 如果是全局模式，且不在白名单中，返回 true
    if (mode === 'global') {
        return true;
    }
    
    // 如果是选择性模式，检查是否在优化名单中
    return optimizeList && optimizeList.some(item => matchUrl(item.url, currentUrl));
}

// 修改初始化部分
chrome.storage.sync.get(['mode', 'enabled', 'maxWidth', 'whitelist', 'optimizeList'], (result) => {
    const currentUrl = window.location.href;
    const whitelist = result.whitelist || [];
    
    // 首先检查是否在白名单中
    if (whitelist.some(item => matchUrl(item.url, currentUrl))) {
        applyOptimization(false);
        return;
    }
    
    // 不在白名单中，根据模式决定是否应用优化
    let shouldEnable = false;
    if (result.mode === 'global' && result.enabled) {
        shouldEnable = true;
    } else if (result.mode === 'selective') {
        const optimizeList = result.optimizeList || [];
        shouldEnable = optimizeList.some(item => matchUrl(item.url, currentUrl));
    }
    
    applyOptimization(shouldEnable, result.maxWidth || 1100);
});

// 修改消息监听部分
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'TOGGLE_OPTIMIZATION') {
        chrome.storage.sync.get(['whitelist', 'optimizeList'], (result) => {
            const currentUrl = window.location.href;
            const whitelist = result.whitelist || [];
            
            // 首先检查白名单
            if (whitelist.some(item => matchUrl(item.url, currentUrl))) {
                applyOptimization(false);
                sendResponse({ success: true });
                return;
            }
            
            // 不在白名单中，根据模式和状态决定是否应用优化
            if (request.mode === 'global') {
                applyOptimization(request.enabled, request.maxWidth);
            } else if (request.mode === 'selective') {
                const optimizeList = result.optimizeList || [];
                const shouldEnable = optimizeList.some(item => matchUrl(item.url, currentUrl));
                applyOptimization(shouldEnable, request.maxWidth);
            }
            
            sendResponse({ success: true });
        });
        return true; // 保持消息通道开启
    }
    
    if (request.type === 'GET_STATUS') {
        chrome.storage.sync.get(['whitelist', 'optimizeList'], (result) => {
            const currentUrl = window.location.href;
            const whitelist = result.whitelist || [];
            const optimizeList = result.optimizeList || [];
            
            const inWhitelist = whitelist.some(item => matchUrl(item.url, currentUrl));
            const inOptimizeList = optimizeList.some(item => matchUrl(item.url, currentUrl));
            
            sendResponse({
                isOptimized: isOptimized,
                inWhitelist: inWhitelist,
                inOptimizeList: inOptimizeList,
                maxWidth: currentMaxWidth
            });
        });
        return true; // 保持消息通道开启
    }
});

// 监听DOM变化，确保动态加载的内容也能被优化
const observer = new MutationObserver((mutations) => {
    if (isOptimized) {
        mutations.forEach(mutation => {
            mutation.addedNodes.forEach(node => {
                if (node.nodeType === 1) { // 元素节点
                    if (node.matches && node.matches('.main-content, .content, #content, main, article, [role="main"], .container, .wrapper')) {
                        node.classList.add('width-optimizer-enabled');
                        if (node.parentElement && node.parentElement !== document.body) {
                            node.parentElement.classList.add('width-optimizer-enabled-parent');
                        }
                    }
                }
            });
        });
    }
});

// 开始观察DOM变化
observer.observe(document.body, {
    childList: true,
    subtree: true
}); 